package com.wanmait.schedule.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.wanmait.schedule.entity.Classes;
import com.wanmait.schedule.entity.Student;
import com.wanmait.schedule.service.ClassesService;
import com.wanmait.schedule.service.StudentService;
import com.wanmait.schedule.util.AjaxResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 学生表 前端控制器
 * </p>
 *
 * @author wanmait
 * @since 2022-12-05
 */
@RestController
@RequestMapping("/student")

public class StudentController {
    @Resource
    private StudentService studentService;
    @Resource
    private ClassesService classesService;
    //根据id查询
    @PostMapping("findById/{id}")
    public AjaxResult studentFindById(@PathVariable("id") Integer id){
        Student sdt = studentService.getById(id);
        if(sdt==null){
            return AjaxResult.error(10001,"失败");
        }
        return AjaxResult.success("成功").put("student",sdt);
    }
    //添加判断身份证
    @PostMapping("identityRepeat")
    public AjaxResult studentIdentityRepeat(@RequestBody String identity){
        System.out.println(identity);
        Boolean flag = studentService.identityRepeat(identity);
        if(flag){
            return AjaxResult.success("空");
        }
        return AjaxResult.error(10001,"已存在");
    }

    //添加、修改
    @PostMapping("save")
    public AjaxResult studentSave(@RequestBody Student student){
        if(student.getId()==null){
          return studentService.add(student)?AjaxResult.success("添加成功"):AjaxResult.error(10001,"添加失败");
        }
        else {
            studentService.updateById(student);
        }
        return AjaxResult.success("添加成功");
    }

    //删除
    @GetMapping("delete/{id}")
    public AjaxResult studentDelete(@PathVariable("id") Integer id){
        boolean flag = studentService.removeById(id);
        if(flag){
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error(10001,"修改失败");
    }
//    批量删除
    @PostMapping("multipleDelete")
    public AjaxResult multipleDelete(@RequestBody Integer[] idList){
        boolean flag = studentService.removeByIds(Arrays.asList(idList));
        if(flag){
            return AjaxResult.success("成功");
        }
        return AjaxResult.error(10001,"失败");
    }

    // 分页 列表 搜索
    @PostMapping("list")
    @RequiresPermissions("manage:student")
    public AjaxResult studentList(@RequestBody Student student,Integer pageNum){
        List<Classes> classesList = classesService.list();
        PageInfo<Student> studentList = studentService.list(student, pageNum);
        return AjaxResult.success("成功")
                .put("studentList",studentList)
                .put("classesList",classesList);
    }

    //学生总数
    @GetMapping("total")
    public AjaxResult totle(){
        return AjaxResult.success("成功",studentService.count());
    }


    //个人中心
    @PostMapping("studentCenter/{id}")
    public AjaxResult studentCenter(@PathVariable("id") Integer id){
        Student student= studentService.studentCenter(id);
        System.out.println(student);
        return AjaxResult.success("成功")
                .put("student",student);
    }

    //个人中心修改密码
    @PostMapping("studentCenterUpdatePass")
    public AjaxResult studentCenterUpdatePass(@RequestBody Student student,String oldPassword){
        Student byId = studentService.getById(student.getId());

        if (byId.getPassword().equals(oldPassword)) {
            studentService.updateById(student);
            return AjaxResult.success("成功");
        }
        return AjaxResult.error(10002,"旧密码错误");
    }
    //个人中心修改头像
    @PostMapping("updatePic")
    public AjaxResult updatePic(@RequestBody Student student){
        if(student.getId()==null){
            studentService.save(student);
        }
        else {
            studentService.updateById(student);
        }
        return AjaxResult.success("成功",student);

    }

    //excel批量添加
    @PostMapping("ExcelAdd")
    public AjaxResult ExcelAdd(@RequestBody List<Student> studentList){
        Boolean aBoolean = studentService.ExcelAdd(studentList);
        return AjaxResult.success("成功");
    }





    //导出指定班级里的学生
    @PostMapping("/export")
    public void export(@RequestBody Integer[] ids,HttpServletResponse response) throws IOException {

        List<Student> list = studentService.findByClassId(ids);
        //我们创建Hutool给我们写好的ExcelWrite
        ExcelWriter wirter = ExcelUtil.getWriter(true);

//        wirter.addHeaderAlias("id","id");
        wirter.addHeaderAlias("name","姓名");
        wirter.addHeaderAlias("sex","性别");
        wirter.addHeaderAlias("identity","身份证");
        wirter.addHeaderAlias("phone","电话");
        wirter.addHeaderAlias("emil","邮箱");
        //hutool默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        wirter.setOnlyAlias(true);
        wirter.write(list,true);
        //将输出的excel文件写出到客户端直接下载
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        // response.setContentType("application/octet-stream;charset=UTF-8;");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        //response.setHeader("Content-Disposition","attachment;filename=test.xls");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream out=response.getOutputStream();
        wirter.flush(out,true);
        //关闭wirter，释放内存
        wirter.close();
        //关机输出servlet流
        IoUtil.close(out);
    }

}
